/*
 * @Description: 工具库
 */

//循环递归获取属性--树形结构
export function recursionArr(targetInfo: any[], target: string = 'name', children: string = 'children', all: boolean = false, resultArr: any[] = []) {
  if (!Array.isArray(targetInfo)) return []
  targetInfo.forEach((item: any) => {
    if (item[children] && item[children].length > 0) {
      if (all) {
        if (item[target]) resultArr.push(item[target])
      }
      recursionArr(item[children], target, children, all, resultArr)
    } else {
      if (item[target]) resultArr.push(item[target]) //取最深处的name
    }
  })
  return resultArr
}

// 批量导出文件流处理成excel文件
export function exportFileStream(res: any, name = '批量导出文件') {
  const blob = new Blob([res], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  const downloadElement = document.createElement('a')
  const href = URL.createObjectURL(blob) //创建下载链接
  downloadElement.href = href
  downloadElement.download = name + '.xlsx'
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

// 获取浏览器地址栏中的携带参数
export function getQueryVariable(variable: any) {
  var query = decodeURIComponent(window.location.search.substring(1))
  var vars = query.split('&')
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] == variable) {
      return pair[1]
    }
  }
  return ''
}

// 对象去重
export function rmDuplicatesByKey(arr: any[], key: string) {
  let obj: any = {}
  let reduce: any[] = []
  reduce = arr.reduce(function (item, next) {
    obj[next[key]] ? '' : (obj[next[key]] = true && item.push(next))
    return item
  }, [])
  return reduce
}

// a标签href下载
export function downloadByTagA(href: string, fileName: string) {
  const downloadElement = document.createElement('a')
  downloadElement.href = href
  downloadElement.download = fileName
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement) // 下载完成移除元素
}

// Blob下载
export function download(name: any, data: any) {
  const blob = new Blob([data])
  const objectURL = URL.createObjectURL(blob)
  let btn: any = document.createElement('a')
  btn.download = name
  btn.href = objectURL
  btn.click()
  URL.revokeObjectURL(objectURL)
  btn = null
}

// 数组匹配指定属性-获取对象
export function matchArrayObj(targetArr: any[], attr: string, val: any) {
  targetArr = Array.isArray(targetArr) ? targetArr : []
  let targetObj = targetArr.find((item: any) => item[attr] == val)
  return targetObj
}

// 数组匹配指定属性-获取对象具体数值
export function matchArrayAttr(targetArr: any[], attr: string, val: any, targetAttr: string, needObj = false) {
  let targetObj = matchArrayObj(targetArr, attr, val)
  if (needObj) return targetObj
  let targetText = targetObj ? targetObj[targetAttr] : undefined
  return targetText
}

// 获取上月
export function getDateMonth() {
  const date = new Date() // 获取时间
  const year = date.getFullYear() // 获取年
  let month: number | string = date.getMonth() // 获取上月
  month = month > 9 ? month : '0' + month
  return year + '-' + month + '-01'
}

// 获取输入时间的月份
export function getFromatDateMonth(dateStr?: any) {
  const date = dateStr ? new Date(dateStr) : new Date() // 获取时间
  console.log('date', date)
  const year = date.getFullYear() // 获取年
  let month: number | string = date.getMonth() + 1 // 获取月
  month = month > 9 ? month : '0' + month
  return year + '-' + month + '-01'
}

// 获取输入时间的年份
export function getFromatDateYear(dateStr?: any) {
  const date = dateStr ? new Date(dateStr) : new Date() // 获取时间
  const year = date.getFullYear() // 获取年
  return year
}

// 生成唯一id
export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

// 格式化轴线数字
export function formatterAxle(value: number) {
  let valStr: string | number = ''
  if (value >= 1000000) {
    valStr = value / 1000000 + '百万'
  } else if (value >= 10000) {
    valStr = value / 10000 + '万'
  } else if (value < 10000) {
    valStr = numberToCurrencyNo(value)
  }
  return valStr
}

// 数字格式化-千位符
export function numberToCurrencyNo(value: number) {
  if (!value) return 0
  // 获取整数部分
  const intPart = Math.trunc(value)
  // 整数部分处理，增加,
  const intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  // 预定义小数部分
  let floatPart = ''
  // 将数值截取为小数部分和整数部分
  const valueArray = value.toString().split('.')
  if (valueArray.length === 2) {
    // 有小数部分
    floatPart = valueArray[1].toString() // 取得小数部分
    return intPartFormat + '.' + floatPart
  }
  return intPartFormat + floatPart
}

export function loadingPromise(timeArr?: any[]) {
  const resTimeArr = timeArr || [108, 152, 200, 300, 400, 461, 500, 600]
  let time = resTimeArr[Math.floor(Math.random() * resTimeArr.length)]
  return new Promise<void>(resolve => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}

// 获取环境变量数据
export interface ImportMetaEnv {
  BASE_URL: string
  MODE: string
  DEV: boolean
  PROD: boolean
  SSR: boolean
  VITE_API_BASEURL: string
}
export type MetaEnvType = keyof ImportMetaEnv
export function getEnvData(): ImportMetaEnv
export function getEnvData<K extends MetaEnvType>(key: K): ImportMetaEnv[K]
export function getEnvData(key?: MetaEnvType) {
  return key ? import.meta.env[key] : import.meta.env
}

// 向上递归查找查找父级祖级-指定属性值
export function findAncestorsWithSameProperty(tree: any[], property: string, value: any, ancestors: any[] = []): any[] {
  if (!tree || !Array.isArray(tree)) return []

  for (const node of tree) {
    if (node[property] === value) {
      ancestors.push(node[property])
      // 添加这一行来保证只获取最近的祖先节点
      break
    }
    if (Array.isArray(node.children) && node.children.length > 0) {
      const result = findAncestorsWithSameProperty(node.children, property, value, ancestors)
      if (result.length > 0) {
        ancestors.push(node[property])
        break
      }
    }
  }

  return ancestors.reverse()
}
